package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVO;
import com.atguigu.gulimall.auth.fegin.MemberFeginService;
import com.atguigu.gulimall.auth.fegin.ThirdPartyFeginService;
import com.atguigu.gulimall.auth.vo.UserLoginVO;
import com.atguigu.gulimall.auth.vo.UserRegistVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @ClassName IndexController
 * @Description TODO
 * @Author 13290
 * @Date 2022/12/9 14:20
 **/
@Controller
public class LoginController {

    @Autowired
    ThirdPartyFeginService thirdPartyFeginService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeginService memberFeginService;

    /**
     * //1.接口防刷
     *
     * //2.校验验证码 redis
     *
     **/
    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("mobile") String mobile){
        //1.校验数据
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + mobile);
        if (!StringUtils.isEmpty(redisCode)){
            Long aLong = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - aLong < 60000){
                //在60秒内
                return R.error(BizCodeEnum.VAILD_SMS_CODE_EXCEPTION.getCode(),BizCodeEnum.VAILD_SMS_CODE_EXCEPTION.getMsg());
            }
        }

        //TODO 接口防刷

        //2.存储redis
        String substring = UUID.randomUUID().toString().substring(0, 5);
        String s = substring + "_" + System.currentTimeMillis();
        //String substring = "爱老虎油";
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + mobile,s,5, TimeUnit.SECONDS);

        //60秒内防止同一个手机号 重复发送

        thirdPartyFeginService.sendCode(mobile,substring);
        return R.ok();
    }


    /**
     * TODO redirectAttributes重定向携带数据,利用session原理.将数据放在session中 只要跳到下一个页面,取出这个数据之后.session里面的数据就会删除
     *
     * TODO　解决分布式下的session问题
     * @author
     * @Description
     * @Date 10:52 2022/12/13
     * @param registVO
     * @param result
     * @param redirectAttributes 模拟重定向携带数据
     * @Return java.lang.String
     **/
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVO registVO, BindingResult result,
                         RedirectAttributes redirectAttributes, HttpSession session){

        if (result.hasErrors()){

            /**
             * .map(r ->{
             *                 String field = r.getField();
             *                 String defaultMessage = r.getDefaultMessage();
             *                 errors.put(field,defaultMessage);
             *
             *             })
             **/
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField,FieldError::getDefaultMessage));

            //session.setAttribute("");
            redirectAttributes.addFlashAttribute("errors",errors);

            //Request method 'post' not supported
            //用户注册 -> /regist[post] -> 转发/reg.html(路径映射,默认都是get方式访问的)

//            转发
//            直接转发
//            return "reg";
//            通过config映射
            //转发会导致重复提交,使用重定向,但是重定向数据不共享
            return "redirect:http://auth.localhost:11111/reg.html";
        }

        //校验验证码
        String code = registVO.getCode();
        //获取redis中的验证码
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + registVO.getPhone());
        if (!StringUtils.isEmpty(s)){

            if (code.equals(s.split("_")[0])){
                //删除原有验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + registVO.getPhone());
                //验证码通过 远程调用服务
                R r = memberFeginService.regist(registVO);
                if (r.getCode() == 0){
                    //成功
                    return "redirect:http://localhost:11111/login.html";
                }else {
                    HashMap<Object, Object> errors = new HashMap<>();
                    errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors",errors);
                    //失败
                    return "redirect:http://auth.localhost:11111/reg.html";
                }
            }else {
                Map<String, String> errors = new HashMap<>();

                errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);

                return "redirect:http://auth.localhost:11111/reg.html";
            }
        }else {
            Map<String, String> errors = new HashMap<>();

            errors.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);

            return "redirect:http://auth.localhost:11111/reg.html";
        }

    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){

        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute == null){
            return "login";
        }
        return "redirect:http://localhost:11111";
    }

    @PostMapping("/login")
    public String login(UserLoginVO loginVO,RedirectAttributes redirectAttributes,HttpSession session){

        //远程
        R login = memberFeginService.login(loginVO);
        if (login.getCode() == 0){
            MemberRespVO data = login.getData("data", new TypeReference<MemberRespVO>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER,data);
            return "redirect:http://localhost:11111";

        }else {
            HashMap<Object, Object> errors = new HashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.localhost:11111/login.html";
        }

    }

}
